package com.gmom.tako.db;

import java.util.ArrayList;
import java.util.List;

import com.gmom.tako.model.Url;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

public class urlDao {
	
	/**
	 * テーブル情報
	 */
	private static final String TABLE_NAME = "url";
	private static final String COLUMN_ID = "_id";
	private static final String COLUMN_TITLE = "title";
	private static final String COLUMN_URL = "url";
	private static final String[] COLUMNS = { COLUMN_ID, COLUMN_TITLE,
			COLUMN_URL };

	private SQLiteDatabase db;

	public urlDao(SQLiteDatabase db) {
		this.db = db;
	}

	/**
	 * 入れる
	 * @param url
	 * @return
	 */
	public long insert(Url url) {
		return db.insert(TABLE_NAME, null, toContentValues(url));
	}

	/**
	 * 更新する
	 * @param url
	 * @return
	 */
	public int update(Url url) {
		String whereClause = COLUMN_ID + "=" + url.get_id();
		return db.update(TABLE_NAME, toContentValues(url), whereClause, null);
	}

	/**
	 * 全件取得
	 * @return
	 */
	public List<Url> findAll() {
		List<Url> urlList = new ArrayList<Url>();

		Cursor c = db.query(TABLE_NAME, COLUMNS, null, null, null, null, null);
		while (c.moveToNext()) {
			urlList.add(toUrl(c));
		}
		return urlList;
	}

	/**
	 * ID検索
	 * @param urlId
	 * @return
	 */
	public Url findById(int urlId) {
		String selection = COLUMN_ID + "=" + urlId;

		Cursor c = db.query(TABLE_NAME, COLUMNS, selection, null, null, null,
				null);
		c.moveToNext();
		return toUrl(c);
	}

	/**
	 * ID指定削除
	 * @param urlId
	 * @return
	 */
	public int delete(int urlId) {
		return db.delete(TABLE_NAME, COLUMN_ID + "=" + urlId, null);
	}

	/**
	 * URLモデルに変換
	 * @param c
	 * @return
	 */
	private Url toUrl(Cursor c) {
		Url url = new Url();
		url.set_id(c.getInt(c.getColumnIndex(COLUMN_ID)));
		url.setTitle(c.getString(c.getColumnIndex(COLUMN_TITLE)));
		url.setUrl(c.getString(c.getColumnIndex(COLUMN_URL)));
		return url;
	}

	/**
	 * ContentValues型に変換
	 * @param url
	 * @return
	 */
	private ContentValues toContentValues(Url url){
		ContentValues values = new ContentValues();
		values.put(COLUMN_TITLE, url.getTitle());
		values.put(COLUMN_URL, url.getUrl());
		return values; 
	}

	/**
	 * URLで検索
	 * @param url
	 * @return
	 */
	public Url findByUrl(String url) {
		String selection = COLUMN_URL + "=" + "'"+url+"'";
		Cursor c = db.query(TABLE_NAME, COLUMNS, selection, null, null, null,
				null);
		c.moveToFirst();
		if (c != null && c.getCount() > 0) {
			//Log.v("findByUrl", "exists " + url);
			return toUrl(c);
		}else{
			//Log.v("findByUrl", "no exists " + url);
		}
		return null;
	}
}
